<%@ page pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="isperp" uri="/WEB-INF/tlds/isperp.tld"%>
<style type="text/css">
.ciRuleItem {
	padding: 3px 2px;
	margin: 3px 1px;
	background: #F3F7F9
}

.ciRuleItemLabel {
	
}
</style>
<div id="agreementContainer" class="box tabbedBox">
	<div class="header">
		<ul>
			<li><a class="current" href="#basicInfo">服务协议</a>
			</li>
			<li data-beforeclick="serviceTarget_beforeClick();"><a
				href="#serviceTarget">考核指标</a>
			</li>
			<li data-beforeclick="serviceTarget_beforeClick(1);"><a
				href="#alarmSetting">自动提醒</a>
			</li>
			<li style="display: none"><a href="#upgradeSetting">升级规则</a></li>
		</ul>
		<h2>&nbsp;</h2>
	</div>
	<div style="padding:0" class="content tabbed">
		<div id="basicInfo">
			<form:form id="serviceAgreementForm" commandName="model"
				cssClass="validate" action="slm/serviceAgreement/save">

				<form:hidden path="id" />
				<input type="hidden" id="editStatus" value="${editStatus}" />
				<h2 class="title">基本信息</h2>
				<table class=" form-table">
					<tbody>
						<tr style="display:none">
							<td class="td1">项目：</td>
							<td class="td2"><form:select path="projectId"
									onchange="projectId_onchange(this);" items="${projects}"
									itemLabel="name" itemValue="id" cssClass="search"
									data-width="300px" /></td>
						</tr>
						<tr>
							<td class="td1">名称：</td>
							<td class="td2"><form:input path="name"
									cssStyle="width:355px" maxlength="100" cssClass="required" />
							</td>
						</tr>
						<tr style="display:none">
							<td class="td1">类型：</td>
							<td class="td2"><form:radiobuttons path="slmType"
									items="${slmTypes}" itemLabel="name" itemValue="name"
									cssClass="" /><label class="required"></label></td>
						</tr>

						<tr >
							<td class="td1">服务响应：</td>
							<td class="td2"><form:radiobutton path="useProjectCalendar" onclick="hideOrShowCalendar(1)"
									value="1" label="项目日历" /> <form:radiobutton onclick="hideOrShowCalendar(2)"
									path="useProjectCalendar" value="0" label="7*24服务"
									cssClass="required" /><label class="required"></label>
							</td>
						</tr>

						<tr  id="slmCalendarTr">

							<td class="td1">工作日历：</td>
							<td class="td2"><form:select path="appCalendarConfigId"
									items="${appCalendars }" itemLabel="name" itemValue="id"></form:select>
							</td>
						</tr>

						<tr style="display:none">
							<td class="td1">服务方式：</td>
							<td class="td2"><form:radiobuttons path="serviceWay"
									items="${serviceWays}" itemLabel="name" itemValue="name"
									cssClass="" /><label class="required"></label></td>
						</tr>
						<tr>
							<td class="td1">合规性目标(%)：</td>
							<td class="td2"><form:input path="goal"
									cssClass="number required" maxlength="5" style="width:100px" />
							</td>
						</tr>
						<tr style="display:none">
							<td class="td1">状态：</td>
							<td class="td2"><form:radiobutton path="slmStatus"
									value="启用" label="启用" checked="true" /> <form:radiobutton
									path="slmStatus" value="禁用" label="禁用" />
							</td>
						</tr>
						<tr>
							<td class="td1">应用对象：</td>
							<td class="td2"><form:radiobuttons path="applyObject"
									cssClass="required" items="${applyObjects}" itemLabel="name"
									itemValue="id" />
							</td>
						</tr>
						<!-- 	<tr>
							<td class="td1">协议卸载：</td>
							<td class="td2"><form:input path="endTargetCondition"
									cssClass="required" />
						</tr> -->
						</tbody>
				</table>


				<h2 class="title">适用范围</h2>
				<table id="tbScorp" class=" form-table"
					style="display:${empty model.id?'':'none'}">
					<tbody>
						<tr style="display:none">
							<td class="td1">用户类型：</td>
							<td class="td2"><form:checkboxes path="userTypes"
									items="${userTypes}" itemLabel="name" itemValue="name" />
							</td>
						</tr>
						<tr>
							<td class="td1">服务目录：</td>
							<td class="td2" id="serviceProductsTd"><form:checkboxes
									path="serviceProducts" items="${serviceProducts}"
									itemLabel="name" itemValue="id" />
							</td>
						</tr>
						<tr>
							<td class="td1">资产类型：</td>
							<td class="td2"><input type="button" id="btnAddCiRule"
								onclick="btnAddCiRule_OnClick()" value="添加资产范围" />
								<div id="ciRule"></div>
							</td>
						</tr>
						<tr>
							<td class="td1">其它条件：</td>
							<td class="td2">

								<table class="form-table">
									<tr>
										<td><select id="fieldName1"
											onchange="fieldName_Change(this);"><option></option>
										</select> <select id="fieldType1">
												<option value="eq">等于</option>
												<option value="neq">不等于</option>
												<option value="cn">包含</option>
												<option value="ncn">不等于</option>
												<option value="gt">大于</option>
												<option value="lt">小于</option>
										</select> <span id="fieldName1Value"></span>
										</td>
									</tr>
									<tr>
										<td><select id="fieldName2"
											onchange="fieldName_Change(this);"><option></option>
										</select> <select id="fieldType2">
												<option value="eq">等于</option>
												<option value="neq">不等于</option>
												<option value="cn">包含</option>
												<option value="ncn">不等于</option>
												<option value="gt">大于</option>
												<option value="lt">小于</option>
										</select> <span id="fieldName2Value"></span>
										</td>
									</tr>
									<tr>
										<td><select id="fieldName3"
											onchange="fieldName_Change(this);"><option></option>
										</select> <select id="fieldType3">
												<option value="eq">等于</option>
												<option value="neq">不等于</option>
												<option value="cn">包含</option>
												<option value="ncn">不等于</option>
												<option value="gt">大于</option>
												<option value="lt">小于</option>
										</select> <span id="fieldName3Value"></span>
										</td>
									</tr>
								</table>
							</td>
						</tr>

					</tbody>
				</table>

				<table class="form-table">
					<tbody>
						<tr>
							<td class="td1">适应范围规则：</td>
							<td class="td2"><form:textarea id="scopeSql" path="scopeSql" />
								<input type="button" id="btnScopeSqlReset"
								onclick="scopeSqlReset_OnClick();"
								style="display:${empty model.id?'none':''}" class="sbutton"
								value="重新设置" /> <input type="button" id="btnScopeSqlGeneral"
								onclick="scopeSql_OnClick();"
								style="display:${empty model.id?'':'none'}" class="sbutton"
								value="生成规则" /> <input type="button" class="sbutton"
								value="测试规则" />
							</td>
						</tr>
						<tr>
							<td class="td1">适应范围说明：</td>
							<td class="td2"><label id="scopeSqlDesc"
								cssStyle="width:80%" />${model.scopeDesc }</label> <form:textarea
									path="scopeDesc" cssStyle="display:none" />
							</td>
						</tr>

					</tbody>
				</table>
				<br>
			</form:form>
			<br> <br>
		</div>

		<div id="serviceTarget">
			<isperp:grid url="slm/serviceTarget/listByAgreement?agreementId="
				gridId="serviceTargetGrid" height="auto" showPager="false"
				showSearchbar="false" gridTitle="考核指标"
				urlExtScript="function(){return $('#id').val();}"
				cusEditUrl="slm/serviceTarget/edit"
				beforeCreateAction="'agreementId='+document.getElementById('id').value"
				ondbClickRowEvent="serviceTargetGrid.edit(rowid);"
				cusDeleteUrl="slm/serviceTarget/delete" cusDialogWidth="500"
				cusDialogHeight="400" sortname="orderNum">
				<jsp:attribute name="toolbar">
	 				<isperp:toolbar id="menuToolbar">
		 				<isperp:button id="serviceTargetGridCreate" icon="icon-plus"
							text="新增考核指标"
							onclick=" if(document.getElementById('id').value){ serviceTargetGrid.create();}else{alert('请先保存协议');}"></isperp:button>
	 				</isperp:toolbar>
				 </jsp:attribute>
				<jsp:body>
					<isperp:column name="id" title="id" hidden="true"></isperp:column>
					<isperp:column name="name" title="指标名称" width="80">
					</isperp:column>
					<%-- <isperp:column name="targetDa" title="起始状态" width="100">
					</isperp:column>
					<isperp:column name="targetDb" title="结束状态" width="100">
					</isperp:column> --%>
					
					<isperp:column name="target" title="考核目标" width="100">
					</isperp:column>
					<isperp:column name="memo" title="备注" width="100">
					</isperp:column>
					<isperp:groupHeaders startColumnName="targetDa" numberOfColumns="2"
						titleText="指标定义"></isperp:groupHeaders>
				</jsp:body>

			</isperp:grid>
		</div>

		<div id="alarmSetting">
			<isperp:grid
				url="slm/alarmSetting/listByAgreement?agreementId=${model.id }"
				gridId="alarmSettingGrid" height="auto" showPager="false"
				showSearchbar="false" gridTitle="自动提醒" cusFormatterActions="true"
				cusEditUrl="slm/alarmSetting/edit"
				beforeCreateAction="'agreementId='+document.getElementById('id').value;"
				ondbClickRowEvent="alarmSettingGrid.edit(rowid);"
				cusDeleteUrl="slm/alarmSetting/delete" cusDialogSize="normal">
				<jsp:attribute name="toolbar">
	 				<isperp:toolbar id="menuToolbar">
		 				<isperp:button id="serviceTargetGridCreate" icon="icon-plus"
							text="新增自动提醒"
							onclick=" if(document.getElementById('id').value){ alarmSettingGrid.create();}else{alert('请先保存协议');}"></isperp:button>
	 				</isperp:toolbar>
				 </jsp:attribute>
				<jsp:body>
					<isperp:column name="id" title="id" hidden="true"></isperp:column>
					<isperp:column name="title" title="标题" width="120">
					</isperp:column>
					<isperp:column name="service_target_name" title="关联考核指标"
						width="90">
					</isperp:column>
					<isperp:column name="type" title="类型" width="60">
					</isperp:column>
					<isperp:column name="description" title="时间(时:分)" width="90">
					</isperp:column>
					<isperp:column name="send_way" title="发送方式" width="80">
					</isperp:column>
					<isperp:groupHeaders startColumnName="type" numberOfColumns="2"
						titleText="发送时间设定"></isperp:groupHeaders>
					
				</jsp:body>

			</isperp:grid>
		</div>

		<div id="upgradeSetting">

			<isperp:grid
				url="slm/upgradeSetting/listByAgreement?agreementId=${model.id }"
				gridId="upgradeSettingGrid" gridTitle="${pageTitle}"
				showPager="false" showSearchbar="false"
				beforeCreateAction="'agreementId='+document.getElementById('id').value;"
				cusEditUrl="slm/upgradeSetting/edit"
				ondbClickRowEvent="upgradeSettingGrid.edit(rowid);"
				cusDeleteUrl="slm/upgradeSetting/delete">

				<jsp:body>
				<isperp:column name="id" title="id" hidden="true"></isperp:column>
				<isperp:column name="service_target_name" title="考核指标" width="80">
				</isperp:column>
				<isperp:column name="type" title="类型" width="150">
				</isperp:column>
				<isperp:column name="distance" title="提前/超时时间" width="80">
				</isperp:column>
				<isperp:column name="step_node_id" title="升级到" width="80">
				</isperp:column>
			</jsp:body>

			</isperp:grid>


		</div>
	</div>


	<isperp:buttonList>
		<button class="submit" onclick="isperp.submitForm();return false;">
			<span class="icon icon-save"></span>提交
		</button>
	</isperp:buttonList>
	<div id="dialogCiTree" title="添加资产类型规则" style="display:none">

		<div id="ciPropertyTreePanel" class="treePanel2"
			style="width:100%;height:280px;">

			<isperp:tree id="ciTree" modal="readonly">
				<isperp:async enable="true" url=""></isperp:async>
			</isperp:tree>
		</div>

		<div style="padding-top:5px">
			<label style="color:red">方式：</label> <span><input
				id="ruleType1" name="ruleType" style="width:30%" checked="checked"
				type="checkbox" value="1" /><label for="ruleType1">是否包含子级</label> </span>
		</div>

	</div>

</div>
<script type="text/javascript">
	var fieldControls;
	
	function hideOrShowCalendar(v)
	{
	   if(v==1)
	   {
	      $("#slmCalendarTr").show();
	   }else
	   {
	      $("#slmCalendarTr").hide();
	   }
	}

	$(document).ready(function() {
	
	    var useProjectCalendar='${model.useProjectCalendar}';
	    if(useProjectCalendar=="false")
	    {
	        $("#slmCalendarTr").hide();
	    }

		//	isperp.initElement("#importContainer");
		var wizCreate = isperp.wizard({
			wizardId : "agreementContainer"
		});

		$("#dialogCiTree").dialog({
			width : 300,
			height : 400,
			autoOpen : false,

			buttons : {
				添加 : addSelectedCiRule,
				关闭 : function() {
					$(this).dialog("close");
				}
			}
		});

		$("input[name='applyObject']").change(function() {
			setApplyObjectEntity();
		});

		var projectId = '${model.projectId}';
		if (projectId == "") {
			$("#projectId").val("");
			$("#projectId").trigger("chosen:updated");
		}

		setRuleSettingStatus();

	});

	/**使用范围设置状态，新增状态下，生成规则条件以及按钮需要显示，编辑状态下需要隐藏，同时“重新设置”等按钮需要显示  **/
	function setRuleSettingStatus() {
		//var status=$("#editStatus").val();
		var status = document.getElementById("editStatus").value;

		if (status == "0") {
			scopeSqlReset_OnClick();
		}
	}

	function setApplyObjectEntity() {
		var entityId = $("input[name='applyObject']:checked").val();

		if (entityId && entityId != "") {
			setApplyObjectCondition(entityId);
		}
	}

	/** 根据实体名设置应用对象条件 **/
	function setApplyObjectCondition(entityId) {
		$.getJSON("db/entity/selectEntityFieldById", {
			id : entityId
		}, function(data) {
			var options = "<option></option>";

			getFieldControls(entityId);

			$(data).each(function(index, item) {
				options += "<option value='"+item.columnName+"'>" + item.name + "</option>";
			});

			$("#fieldName1,#fieldName2,#fieldName3").html(options);
			$("#fieldName1,#fieldName2,#fieldName3").trigger("chosen:updated");
		});
	}

	/** 增加所选的Ci规则 **/
	function addSelectedCiRule() {

		var ruleType = $("input[name='ruleType']:checked").val();

		var nodes = ciTree.zTree.getSelectedNodes(true);
		if (nodes && nodes.length > 0) {

			var node = nodes[0];
			var str = "";
			if (ruleType == "1") {
				str = "treenode_name_path LIKE '" + node.treenodeNamePath + "%'";
			} else {
				str = "treenode_name_path = '" + node.treenodeNamePath + "'";
			}

			var labelclick = '<a href="javascript:void(0);" onclick="deleteciRuleItem(\'' + node.id + '\')"><span class="icon icon-remove "></span></a>';

			var label = "<div class='ciRuleItem' id='div_"+node.id+"'>" + labelclick + "<lable class='ciRuleItemLabel'>" + str + "</label></div>";
			$("#ciRule").append(label);

			//$(this).dialog("close");
		} else {
			alert("请选择一个类型节点！");
		}

	}

	function deleteciRuleItem(id) {

		$("#div_" + id).remove();
	}

	/**根据实体获取实体字段的控件**/
	function getFieldControls(entityId) {
		$.getJSON("db/entityFieldControl/listByEntityId", {
			entityId : entityId,
			slmField : "1"
		}, function(data) {
			fieldControls = data;
		});
	}

	/** 字段修改事件 **/
	function fieldName_Change(obj) {
		var $el = $(obj);

		var fieldNameId = $el.attr("id");
		$("#" + fieldNameId + "Value").empty();
		var elVal = $el.val();
		if (elVal) {
			var elControl;
			var fieldControlsLen = fieldControls.length;
			for ( var i = 0; i < fieldControlsLen; i++) {

				if (fieldControls[i].column_name == elVal) {
					elControl = fieldControls[i];
					break;
				}
			}

			if (elControl) {

				if ("select" == elControl.control_type) {
					var url = "db/dynamicControl/getDatasource";
					$.getJSON(url, {
						datasourceEntityId : elControl.datasource_entity_id,
						valueField : elControl.value_field,
						displayField : elControl.display_field,
						filter : elControl.filter
					}, function(result) {
						var options = "";
						$(result).each(function(index, item) {
							options += "<option value='"+item[elControl.value_field]+"'>" + item[elControl.display_field] + "</option>";
						});

						$("#" + fieldNameId + "Value").html("<select id='"+fieldNameId+"Control' style='height:24px;width:153px'>" + options + "</select>");
						$("#" + fieldNameId + "Control").trigger("chosen:updated");

					});
				}
			} else {
				$("#" + fieldNameId + "Value").append("<input id='"+fieldNameId+"Control' type='text' />");
			}
		}
	}

	/** 增加Ci规则按钮点击 **/
	function btnAddCiRule_OnClick() {

		//var treeObj = $.fn.zTree.getZTreeObj("ciTree");
		ciTree.zTree.setting.async.url = "configuration/category/getTree";

		ciTree.reload();
		$("#dialogCiTree").dialog("open");
	}

	function scopeSqlReset_OnClick() {
		setApplyObjectEntity();
		$("#btnScopeSqlReset").hide();
		$("#btnScopeSqlGeneral,#tbScorp").show();

	}

	function scopeSql_OnClick() {

		var sql = "1=1 ";

		var sqlDesc = "";

		var userTypeSqlDesc = "";
		var userTypeSql = "";

		$("input[name='userTypes']:checked").each(function(index, item) {

			if (userTypeSql != "") {
				userTypeSql += " OR ";
				userTypeSqlDesc += "或";
			}
			userTypeSql += " user_type='" + item.value + "' ";
			userTypeSqlDesc += item.value;
		});

		if (userTypeSql) {
			userTypeSql = "(" + userTypeSql + ")";
			sql += " AND " + userTypeSql;
			if (userTypeSqlDesc != "") {
				sqlDesc += "（用户类型为：" + userTypeSqlDesc + "）";
			}
		}

		var serviceProductSqlDesc = "";
		var serviceProductSql = "";
		$("input[name='serviceProducts']:checked").each(function(index, item) {
			if (serviceProductSql != "") {
				serviceProductSql += " OR ";
				serviceProductSqlDesc += "或";
			}

			serviceProductSql += "service_product='" + item.value + "' ";
			serviceProductSqlDesc += $(item).siblings().text();
		});

		if (serviceProductSql) {
			serviceProductSql = "(" + serviceProductSql + ")";
			sql += " AND " + serviceProductSql;
			if (serviceProductSqlDesc != "") {
				sqlDesc += "并且（服务产品为：" + serviceProductSqlDesc + "）";
			}
		}

		var ciSql = "";
		var ciSqlDesc = "";

		$("#ciRule .ciRuleItemLabel").each(function(index, item) {
			var elTxt = $(this).text();
			ciSql += " AND (" + elTxt + ")";
			ciSqlDesc += "并且（" + elTxt.replace("LIKE", "包含").replace("treenode_name_path", "资产分类") + "）";
		});

		if (ciSql) {
			sql += ciSql;
			sqlDesc += ciSqlDesc;
		}

		var otherSql = "";
		var otherSqlDesc = "";
		for ( var i = 0; i < 3; i++) {
			var $fieldName = $("#fieldName" + i);
			var $fieldNameVal = $fieldName.val();
			if ($fieldNameVal && $fieldNameVal != "") {

				otherSql += " AND ( " + $fieldNameVal + conventSqlCondition($("#fieldType" + i).val(), $("#fieldName" + i + "Control").val()) + " ) ";

				otherSqlDesc += "并且（" + $fieldName.find("option:selected").text() + $("#fieldType" + i).find("option:selected").text() + $("#fieldName" + i + "Control").val() + "）";
			}
		}

		if (otherSql) {
			sql += otherSql;
			sqlDesc += otherSqlDesc;
		}

		$("#scopeSql").text(sql);
		$("#scopeSqlDesc").text(sqlDesc);
		$("#scopeDesc").val(sqlDesc);
	}

	function conventSqlCondition(condition, value) {
		switch (condition) {
		case "eq":
			return "='" + value + "'";
		case "neq":
			return "<>'" + value + "'";
		case "cn":
			return " LIKE '%" + value + "'";
		case "ncn":
			return " 	NOT LIKE '%" + value + "'";
		case "gt":
			return ">'" + value + "'";
		case "lt":
			return "<'" + value + "'";
		}
		return "";
	}

	function projectId_onchange(obj) {
		var $this = $(obj);
		$.getJSON("project/service/getByProjectId", {
			projectId : $this.val()
		}, function(data) {
			if (data && data instanceof Array) {

				var html = "";
				$(data).each(function(index, item) {
					html += "<span><input id='serviceProducts"+index+"' name='serviceProducts' type='checkbox' value='"+item.id+"'/><label for='serviceProducts"+index+"'>" + item.code + '-' + item.name + "</label></span>";
				});
				$("#serviceProductsTd").html(html);
				isperp.initElement("#serviceProductsTd");
			}
		});
	}

	function serviceTarget_beforeClick(way) {
		if (way == 1) {
			if (0 == serviceTargetGrid.jqGrid.getGridParam("reccount")) {
				isperp.alert("请添加考核指标！");
				return false;
			}

		}

		return isperp.submitForm({
			formId : "serviceAgreementForm",
			forceSync : true,
			success : function() {
				isperp.reloadParentControl();
			}
		});

	}
</script>